import { Col, Empty, Row, Spin, Timeline, message, Space, Button, Tooltip } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import cls from 'classnames';
import { ContractManageAPI } from '../common/type';
import { useContext, useEffect, useState } from 'react';
import { getMcontractProcessListService } from '../services';
import { ConractControllerContext } from '../common';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import MyIcon from '@/components/MyIcon';
import { UpCircleOutlined, DownCircleOutlined } from '@ant-design/icons';
import { capitalDirType, nodePayStateType, payTypeStr } from '../mconfig';
import { onMouseOutBtn, getUserID, getFileNameByPath, downloadTemplate, newGetFileNameNotType, priceFormat } from '@/utils';
import { EditOutlined } from '@ant-design/icons';
import { OpenPerformanceModal } from './OpenPerformanceModal';

export const DetailInfoViewTabsNode: React.FC<ContractManageAPI.IDetailInfoViewTabsNode> = ({
  tabsPaneInfoObj,
  allOpenChildren,
  changeOpenChildren,
  clickOpenClose,
}) => {
  /** 签发提示框 */
  const [performanceModal, setOpenPerformanceModal] = useState<Record<string, any>>({
    checkRowObj: {},
    isShowModal: false,
  });

  /** 引入上下文 */
  const { locationState, styleFixCls, contractDetailInfo, curRes } = useContext(ConractControllerContext);

  /** 获取数据回调 */
  const processCallback = (res: any) => {
    if (res && res?.msgFlag) {
      if (res?.obj?.length > 0 && allOpenChildren?.openIdKey?.length == 0) {
        const allOpenIDList: string[] = res?.obj?.map((item: any) => item?.id);
        const changeOpenObj = {
          allOpenKeys: allOpenIDList,
          openIdKey: [allOpenIDList?.[0]],
        };
        changeOpenChildren(changeOpenObj);
      }
    } else {
      message.error(res?.message);
    }
  };

  /** 引入获取数据接口 */
  const { getMcontractProcessListData, getMcontractProcessListLoading, getMcontractProcessListRun } = getMcontractProcessListService(processCallback);

  /** 数据初始化 */
  useEffect(() => {
    if (tabsPaneInfoObj?.tabKeyType == 'nodePane') {
      getMcontractProcessListRun({
        id: locationState?.pageInfo?.pID ? locationState?.pageInfo?.pID : locationState?.pageInfo?.id,
      });
    }
  }, [tabsPaneInfoObj, locationState]);

  /** 刷新页面 */
  const reloadManage = () => {
    getMcontractProcessListRun({
      id: locationState?.pageInfo?.pID ? locationState?.pageInfo?.pID : locationState?.pageInfo?.id,
    });
  };

  return (
    <Spin spinning={getMcontractProcessListLoading}>
      <div className="commonTabsBodyDom">
        <div className={'tabsBodyInfoDom'}>
          {getMcontractProcessListData?.length > 0 ? (
            <ScrollBarLayout style={{ padding: '5px 20px' }}>
              <div className={styleFixCls + 'contractTimeLineSty'}>
                <Timeline>
                  {getMcontractProcessListData?.map((item: any, index: number) => {
                    let urlArray = item?.attachURL?.split('||');
                    let itemUrl = urlArray?.map((i) => i);
                    return (
                      <Timeline.Item
                        key={`${item?.id}-${index}`}
                        dot={allOpenChildren?.openIdKey?.includes(item?.id) ? <MyIcon style={{ fontSize: 18 }} type="icon-time-circle" /> : null}
                      >
                        <div style={{ margin: '5px 0px' }}>
                          于&nbsp;
                          <span className={styleFixCls + 'contractTimeLineSty-titleTimeBoxSty'}>{item?.createTime || '--'}</span>
                          &nbsp;创建，履行情况如下：
                          <a
                            onClick={() => {
                              clickOpenClose(item?.id, allOpenChildren, changeOpenChildren);
                            }}
                          >
                            {allOpenChildren?.openIdKey?.includes(item?.id) ? <UpCircleOutlined /> : <DownCircleOutlined />}
                          </a>
                        </div>
                        {allOpenChildren?.openIdKey?.includes(item?.id) && (
                          <div className={`${styleFixCls}contractTimeLineSty-agreeBodyBox`}>
                            <Row
                              className={cls(
                                pageStyles['commonDlListSty'],
                                `${styleFixCls}contractTimeLineSty-agreeBodyBox-rowBoxNode`,
                                `${styleFixCls}operateBtnAnimarion`,
                              )}
                            >
                              <Col span={12}>
                                <dt>涉及款项</dt>：
                                <dd>
                                  <span style={{ color: item?.payFlag == 0 ? 'red' : item?.payFlag == 1 ? '#90EE90' : '--' }}>
                                    {item?.payFlag == 0 ? '否' : item?.payFlag == 1 ? '是' : '--'}
                                  </span>
                                </dd>
                              </Col>

                              {item?.payFlag == 1 && (
                                <>
                                  <Col span={12}>
                                    <dt>款项类别</dt>：<dd>{payTypeStr(item.payType)}</dd>
                                  </Col>
                                  <Col span={12}>
                                    <dt>收付款比例</dt>：
                                    <dd>
                                      <span style={{ fontWeight: 700, color: '#096dd9' }}>{item?.payNum ? `${item?.payNum}` : '0'}</span>
                                      &nbsp;%
                                    </dd>
                                  </Col>
                                  <Col span={12}>
                                    <dt>收付款金额</dt>：
                                    <dd>
                                      <span style={{ fontWeight: 700, color: '#096dd9' }}>{item?.paySum ? `${priceFormat(item?.paySum)}` : '0.00'}</span>
                                      &nbsp;元
                                    </dd>
                                  </Col>
                                  <Col span={12}>
                                    <dt>资金流向</dt>：<dd>{capitalDirType(item.capitalDir)}</dd>
                                  </Col>
                                </>
                              )}

                              <Col span={12}>
                                <dt>执行状态</dt>：<dd>{nodePayStateType(item.payState)}</dd>
                              </Col>
                              <Col span={12}>
                                <dt>节点描述</dt>：<dd>{item.payExplain || '--'}</dd>
                              </Col>
                              {item.finishExplain && (
                                <Col span={24}>
                                  <dt>情况说明</dt>：<dd>{item.finishExplain || '--'}</dd>
                                </Col>
                              )}
                              {item.attachURL && (
                                <Col span={24}>
                                  <dt>佐证材料</dt>：
                                  <dd>
                                    <div style={{ width: '100%', display: 'flex' }}>
                                      {itemUrl?.map((item: any, index: number) => {
                                        return (
                                          <span key={`${index}-word-payURL`}>
                                            <Tooltip title={getFileNameByPath(item)}>
                                              <a
                                                onClick={() => {
                                                  downloadTemplate('/purchaseNeedController/downloadFile', getFileNameByPath(item), item, () => {});
                                                }}
                                              >
                                                <MyIcon type="icon-file-text-fill" />
                                                &nbsp;
                                                {newGetFileNameNotType(item, 7)}
                                              </a>
                                              {itemUrl?.length - 1 == index ? '' : '，'}
                                            </Tooltip>
                                          </span>
                                        );
                                      })}
                                    </div>
                                  </dd>
                                </Col>
                              )}
                              {contractDetailInfo?.ownerID == getUserID() &&
                                item.payFlag == 0 &&
                                (item.payState == 0 || item.payState == 1 || item.payState == 2) &&
                                curRes[`/contractController/finishProcess`] && (
                                  <Space
                                    direction="vertical"
                                    size={[0, 8]}
                                    className={`${styleFixCls}operateBtnAnimarion-editDelOtherBtn`}
                                    style={{
                                      top: '12%',
                                    }}
                                  >
                                    <Button
                                      onMouseOut={onMouseOutBtn}
                                      onClick={() => {
                                        setOpenPerformanceModal({
                                          isShowModal: true,
                                          checkRowObj: item,
                                        });
                                      }}
                                      icon={<EditOutlined />}
                                    >
                                      完成
                                    </Button>
                                  </Space>
                                )}
                            </Row>
                          </div>
                        )}
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
              </div>
            </ScrollBarLayout>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          )}
        </div>
      </div>
      {/* 履约记录弹框 */}
      {performanceModal?.isShowModal && (
        <OpenPerformanceModal
          onClose={() => {
            setOpenPerformanceModal({
              isShowModal: false,
              selectRow: {},
            });
          }}
          selectRowInfo={performanceModal?.checkRowObj}
          reloadManage={reloadManage}
        />
      )}
    </Spin>
  );
};
